<?php

use Elasticsearch\ClientBuilder as ElasticsearchClient;
use Handlers\YopurmaqHandler;

require_once __DIR__ . '/vendor/autoload.php';

ini_set('memory_limit', -1);

$config = require_once __DIR__ . '/configs/config.php';

$instanceConfig = require_once __DIR__ . '/configs/yopurmaq.php';

$dsn = $instanceConfig['database']['dsn'];
$user = $instanceConfig['database']['user'];
$password = $instanceConfig['database']['password'];

$dc = new Nette\Database\Connection($dsn, $user, $password);

$handler = new YopurmaqHandler($instanceConfig['elasticsearch']['hosts'], null);

function bulk_insert_information($connect, $handler) {

  $table = 'information';
  $perPage = 1000;
  $total = $connect->fetchField("select count(*) as count from information");
  $totalPage = ceil($total / $perPage);

  echo "{$table}表信息总数：", $total, ', 总页数：', $totalPage, PHP_EOL;

  echo "开始获取{$table}表数据...", PHP_EOL;

  $startTime = microtime(true);

  for ($curPage = 1;$curPage <= $totalPage;$curPage++) {
    $offset = ($curPage - 1) * $perPage;

    echo "{$table}当前页：", $curPage . '/' . $totalPage, ', 偏移量: ', $offset, PHP_EOL;

$sql = <<<EOD
select 
 information.id, 
 information.uuid, 
 updated_at, 
 changed_at, 
 deleted, 
 status, 
 category_id, 
 city_id, 
 district_id, 
 created_individual_member_id, 
 buy_status, 
 title, 
 thumb, 
 video, 
 information_content.content
from information, information_content 
where information.uuid = information_content.uuid 
order by information.id desc
limit ?, ?
EOD;
    $rows = $connect->fetchAll($sql, $offset, $perPage);

    $totalCount = count($rows);
    
    echo "{$table}当前获取数量：", $totalCount, PHP_EOL;

    foreach ($rows as $row) {
      
      foreach ($row as $name => $value) {
        $row[$name] = $handler->changeFieldValueType($name, $value);
      }

      $handler->insertOrUpdate((array)$row);
    }

    unset($rows);

    echo '当前使用内存：', memory_get_usage(), PHP_EOL;
  }

  $endTime = microtime(true);
  $runTime = floor($endTime - $startTime) / 60;

  echo "{$table}表获取完毕！共花费: ", $runTime . '分钟' ,PHP_EOL;
}

bulk_insert_information($dc, $handler);



